<?php

namespace app\api\controller;

use app\api\model\OrderCommon;
use app\api\model\Topup;
use app\api\model\VipOrder;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use think\Db;

class Wechatwap extends Common
{
    private $options;
    
    public function _initialize()
    {
        $this->options = [
            'app_id' => getenv('WECHAT_APPID2'),
            'payment' => [
                'merchant_id'        => getenv('WECHAT_MERCHANTID'),
                'key'                => getenv('WECHAT_KEY'),
                'notify_url'         => url('api/Wechatwap/notify', '', '', true),
                'return_url'         => url('api/Wechatwap/returnurl', '', '', true),
            ],
            'guzzle' => [
                'verify' => false,
            ],
        ];
    }
    
    public function app($order_sn)
    {
        $result = $this->check($order_sn);
        
        if ($result['code'] != 200) {
            return $this->miss($result['msg']);
        }
        
        $total_amount = $result['data']['total_amount'];
        
        $attributes = [
            'trade_type'       => 'MWEB',
            'body'             => '账户充值',
            'detail'           => '账户充值',
            'out_trade_no'     => $order_sn,
            'total_fee'        => $total_amount * 100,
        ];
        
        $order = new Order($attributes);
        
        $app = new Application($this->options);
        
        $payment = $app->payment;
        
        $result = $payment->prepare($order);
        
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            
            $mweb_url = $result->mweb_url . "&redirect_url=" . $this->options['payment']['return_url'];
            $mweb_url = $result->mweb_url . "&redirect_url=" . 'http://www.nihaozaima.cn/api/Wechatwap/returnurl';
            $data['mweb_url'] = $mweb_url;
            
            return $this->pass($data);
        } else {
            return $this->miss($result->return_msg);
        }
    }
    
    private function check($out_trade_no)
    {
        $state = 0;
        
        $data = (new Topup)->master()->where(['numbers' => $out_trade_no, 'state' => 0])->find();
        
        if ($data) {
            $state = 1;
            $money = $data['price'];
        }
        
        if (!$state) {
            $data = (new OrderCommon)->master()->where(['number' => $out_trade_no, 'status' => 0])->find();
            
            if ($data) {
                $state = 1;
                $money = $data['money'];
            }
        }

        if (!$state) {
            $data = Db::name('mall_order')->master()->where(['number' => $out_trade_no, 'status' => 0])->find();
            
            if ($data) {
                $state = 1;
                $money = $data['money'];
            }
        }
        
        if (!$state) {
            $data = Db::name('order_of_service')->master()->where(['number' => $out_trade_no, 'paystate' => 0, 'state' => 0])->find();
            
            if ($data) {
                $state = 1;
                $money = $data['price'];
            }
        }
        
        if (!$state) {
            $data = Db::name('user_flag')->master()->where(['number' => $out_trade_no, 'paystate' => 0, 'status' => 0])->find();
            
            if ($data) {
                $state = 1;
                $money = $data['price'];
            }
        }

        if (!$state) {
            $data = Db::name('user_address_red_packet')->master()->where(['number' => $out_trade_no, 'type' => 1, 'paystate' => 0])->find();
            
            if ($data) {
                $state = 1;
                $money = $data['totalprice'];
            }
        }

        if (!$state) {
            $data = Db::name('order_of_addressgood')->master()->where(['number' => $out_trade_no, 'status' => 0, 'paystate' => 0])->find();
            
            if ($data) {
                $state = 1;
                $money = $data['price'];
            }
        }
        
        if (!$state) {
            $data = Db::name('activity_join')->master()->where(['number' => $out_trade_no, 'paystate' => 0])->find();
            
            if ($data) {
                $state = 1;
                $money = $data['price'];
            }
        }
        
        if (!$state) {
            return ['code' => 400, 'msg' => '订单不存在'];
        } else {
            return ['code' => 200, 'data' => ['total_amount' => $money]];
        }
    }
    
    public function returnurl()
    {
        $name = getenv('APP_NAME');
        
        $this->assign('name', $name);
        
        return $this->fetch();
    }
    
    public function notify()
    {
        $app = new Application($this->options);
        
        return $app->payment->handleNotify(function($notify, $successful)
        {
            if ($successful) {
                $attach = [];
                if (isset($notify['attach'])) {
                    parse_str($notify['attach'], $attach);
                }
                $notify['other_data'] = $attach;
                $result = OrderCommon::notify($notify['out_trade_no'], $notify);
            }
            return true;
        });
    }
}